package com.geek.novel.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具
 * @Author Hydra
 * @Date 2022/4/20 22:26
 */
public class AesEncryptUtil {

    private static final String iv = "0123456789ABCDEF";//偏移量字符串必须是16位 当模式是CBC的时候必须设置偏移量
    private static final String SecretKey = "0987654321FEDCBA1234567890ABCDEF";
    private static final String Algorithm = "AES";
    private static final String AlgorithmProvider = "AES/CBC/PKCS5Padding"; //算法/模式/补码方式

    public static byte[] generatorKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(Algorithm);
        keyGenerator.init(256);//默认128，获得无政策权限后可为192或256
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }

    public static IvParameterSpec getIv() throws UnsupportedEncodingException {
        return new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 加密
     * @param src   加密字符串
     * @param key   key
     */
    public static byte[] encrypt(String src, byte[] key) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key, Algorithm);
        IvParameterSpec ivParameterSpec = getIv();
        Cipher cipher = Cipher.getInstance(AlgorithmProvider);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
        return cipher.doFinal(src.getBytes(StandardCharsets.UTF_8));
    }


    /**
     * 解密
     * @param src 原密码
     * @param key 解密后的byte数组
     */
    public static byte[] decrypt(String src, byte[] key) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key, Algorithm);
        IvParameterSpec ivParameterSpec = getIv();
        Cipher cipher = Cipher.getInstance(AlgorithmProvider);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        byte[] hexBytes = hexStringToBytes(src);
        return cipher.doFinal(hexBytes);
    }

    /**
     * 将byte转换为16进制字符串
     * @param src   加密模板
     */
    public static String byteToHexString(byte[] src) {
        StringBuilder sb = new StringBuilder();
        for (byte b : src) {
            int v = b & 0xff;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                sb.append("0");
            }
            sb.append(hv);
        }
        return sb.toString();
    }

    /**
     * 将16进制字符串装换为byte数组
     */
    public static byte[] hexStringToBytes(String hexString) {
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] b = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            b[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return b;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 直接传入psd然后解码进行验证使用
     * @param psd 前台传过来的String 加密后的字符串
     */
    public static String decrypt(String psd) {
        try {
            byte[] key = SecretKey.getBytes(StandardCharsets.UTF_8);
            return new String(decrypt(psd, key));
        } catch (Exception e) {
            throw new RuntimeException("账号密码解密失败: "+e.getMessage()+"; password: "+psd, e);
        }
    }

    /**
     * 传入psd然后加密
     * @param psd 前台传过来的String 加密前的字符串
     */
    public static String encrypt(String psd) {
        try {
            byte[] key = SecretKey.getBytes(StandardCharsets.UTF_8);
            return byteToHexString(encrypt(psd, key));
        } catch (Exception e) {
            throw new RuntimeException("账号密码加密失败: "+e.getMessage()+"; password: "+psd, e);
        }
    }


    public static void main(String[] args) throws Exception {
        String passwordAES = "19573590a730886e5848be5f7d9f7571";
        String decrypt = AesEncryptUtil.decrypt(passwordAES);
        System.out.println(decrypt);

        String password = "password";
        String encrypt = AesEncryptUtil.encrypt(password);
        System.out.println(encrypt);
    }

}
